package com.chen.subject.domain.service.impl;

import com.alibaba.fastjson.JSON;
import com.chen.subject.common.entity.PageResult;
import com.chen.subject.common.enums.IsDeletedFlagEnum;
import com.chen.subject.common.enums.SubjectLikedStatusEnum;
import com.chen.subject.common.util.LoginUtil;
import com.chen.subject.domain.convert.SubjectLikedBOConverter;
import com.chen.subject.domain.entity.SubjectLikedBO;
import com.chen.subject.domain.entity.SubjectLikedMessage;
import com.chen.subject.domain.redis.RedisUtil;
import com.chen.subject.domain.service.SubjectLikedDomainService;
import com.chen.subject.infra.basic.entity.SubjectInfo;
import com.chen.subject.infra.basic.entity.SubjectLiked;
import com.chen.subject.infra.basic.service.SubjectInfoService;
import com.chen.subject.infra.basic.service.SubjectLikedService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;

import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 题目点赞表 领域service实现了
 * @author: ChenFY
 * @date: 2024/6/27
 */

@Service
@Slf4j
public class SubjectLikedDomainServiceImpl implements SubjectLikedDomainService {
    @Resource
    private SubjectLikedDomainService subjectLikedDomainService;

    @Resource
    private RedisUtil redisUtil;
    @Resource
    private SubjectLikedService subjectLikedService;
    @Resource
    private RocketMQTemplate rocketMQTemplate;

    @Resource
    private SubjectInfoService subjectInfoService;
    private static final String SUBJECT_LIKED_KEY = "subject.liked";

    private static final String SUBJECT_LIKED_COUNT_KEY = "subject.liked.count";

    private static final String SUBJECT_LIKED_DETAIL_KEY = "subject.liked.detail";
    @Override
    public void add(SubjectLikedBO subjectLikedBO) {
        //获取题目的id
        Long subjectId = subjectLikedBO.getSubjectId();
        //获取点赞的人的id
        String likeUserId = subjectLikedBO.getLikeUserId();
        //获取点赞情况（1为点赞，0为未点赞）
        Integer status = subjectLikedBO.getStatus();
        //不使用mq
//        String hashKey = buildSubjectLikedKey(subjectId.toString(), likeUserId);
//        redisUtil.putHash(SUBJECT_LIKED_KEY,hashKey,status);
        //mq 发送消息实体
        SubjectLikedMessage subjectLikedMessage = new SubjectLikedMessage();
        subjectLikedMessage.setSubjectId(subjectId);
        subjectLikedMessage.setLikeUserId(likeUserId);
        subjectLikedMessage.setStatus(status);
        rocketMQTemplate.convertAndSend("subject-liked",JSON.toJSONString(subjectLikedMessage));
        //题目被那些人点赞
        String detailKey = SUBJECT_LIKED_DETAIL_KEY + "." + subjectId + "." + likeUserId;
        //题目的key
        String countKey = SUBJECT_LIKED_COUNT_KEY + "." + subjectId;
        //点赞时
        if (SubjectLikedStatusEnum.LIKED.getCode() == status) {
            redisUtil.increment(countKey, 1);
            redisUtil.set(detailKey,"1");
        }else {
            //获取点赞数量
            Integer count = redisUtil.getInt(countKey);
            //如果点赞数量为0不做处理
            if (Objects.isNull(count) || count <= 0) {
                return;
            }
            redisUtil.increment(countKey, -1);
            //取消点赞删除key
            redisUtil.del(detailKey);
        }

    }
    private String buildSubjectLikedKey(String subjectId, String userId) {
        return subjectId + ":" + userId;
    }
    @Override
    public Boolean isLiked(String subjectId, String userId) {
        //题目被那些人点赞
        String detailKey = SUBJECT_LIKED_DETAIL_KEY + "." + subjectId + "." + userId;
        return redisUtil.exist(detailKey);
    }

    @Override
    public Integer getLikedCount(String subjectId) {
        String countKey = SUBJECT_LIKED_COUNT_KEY + "." + subjectId;
        //获取题目的点赞数量
        Integer count = redisUtil.getInt(countKey);
        if (Objects.isNull(count) || count <= 0) {
            return 0;
        }
        return count;
    }

    @Override
    public Boolean update(SubjectLikedBO subjectLikedBO) {
        return null;
    }

    @Override
    public Boolean delete(SubjectLikedBO subjectLikedBO) {
        return null;
    }

    /**
     * 同步点赞数据
     */
    @Override
    public void syncLiked() {
        Map<Object, Object> subjectLikedMap = redisUtil.getHashAndDelete(SUBJECT_LIKED_KEY);
        if (log.isInfoEnabled()) {
            log.info("syncLiked.subjectLikedMap:{}", JSON.toJSONString(subjectLikedMap));
        }
        if (MapUtils.isEmpty(subjectLikedMap)) {
            return;
        }
        //批量同步到数据库
        List<SubjectLiked> subjectLikedList = new LinkedList<>();

        subjectLikedMap.forEach((key,val)->{
            SubjectLiked subjectLiked = new SubjectLiked();
            //将key的格式转换为题目id+点赞人  的格式
            String[] keyArr = key.toString().split(":");
            String subjectId = keyArr[0];
            String likedUser = keyArr[1];
            //题目id
            subjectLiked.setSubjectId(Long.valueOf(subjectId));
            //点赞人
            subjectLiked.setLikeUserId(likedUser);
            //点赞状态
            subjectLiked.setStatus(Integer.valueOf(val.toString()));
            //删除状态
            subjectLiked.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
            subjectLikedList.add(subjectLiked);
        });

        subjectLikedService.batchInsertOrUpdate(subjectLikedList);
    }

    /**
     * 查询我的点赞列表
     */
    @Override
    public PageResult<SubjectLikedBO> getSubjectLikedPage(SubjectLikedBO subjectLikedBO) {
        PageResult<SubjectLikedBO> pageResult = new PageResult<>();
        //pageNo
        pageResult.setPageNo(subjectLikedBO.getPageNo());
        //pageSize
        pageResult.setPageSize(subjectLikedBO.getPageSize());
        //起始页
        int start = (subjectLikedBO.getPageNo() - 1) * subjectLikedBO.getPageSize();
        SubjectLiked subjectLiked = SubjectLikedBOConverter.INSTANCE.convertBOToEntity(subjectLikedBO);
        //用户id
        subjectLiked.setLikeUserId(LoginUtil.getLoginId());
        //点赞题目的数量
        int count = subjectLikedService.countByCondition(subjectLiked);
        //如果为0，返回pageResult
        if (count == 0) {
            return pageResult;
        }
        //分页查询like表
        List<SubjectLiked> subjectLikedList = subjectLikedService.queryPage(subjectLiked, start,
                subjectLikedBO.getPageSize());
        //转换为BO返回
        List<SubjectLikedBO> subjectInfoBOS = SubjectLikedBOConverter.INSTANCE.convertListInfoToBO(subjectLikedList);

        subjectInfoBOS.forEach(info -> {
            //根据题目id去查询题目信息
            SubjectInfo subjectInfo = subjectInfoService.queryById(info.getSubjectId());
            //设置题目的名字到BO
            info.setSubjectName(subjectInfo.getSubjectName());
        });
        pageResult.setRecords(subjectInfoBOS);
        pageResult.setTotal(count);
        return pageResult;
    }

    /**
     * mq同步点赞
     */
    @Override
    public void syncLikedByMsg(SubjectLikedBO subjectLikedBO) {
        List<SubjectLiked> subjectLikedList = new LinkedList<>();
        SubjectLiked subjectLiked = new SubjectLiked();
        //题目id
        subjectLiked.setSubjectId(subjectLikedBO.getSubjectId());
        //点赞人
        subjectLiked.setLikeUserId(subjectLikedBO.getLikeUserId());
        //点赞状态
        subjectLiked.setStatus(subjectLikedBO.getStatus());
        //删除状态
        subjectLiked.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        subjectLikedList.add(subjectLiked);
        subjectLikedService.batchInsertOrUpdate(subjectLikedList);
    }
}
